Vyom XML Course

Total Page:16

File Type:pdf, Size:1020Kb

Vyom XML Course

Vyom XML Course

Explore the exciting world of XML!

Vyom Technosoft Pvt. Ltd. Company Confidential

Version: 1.0 Designed By: Amit Mathur [email protected] Approved By: Rakesh Barnwal [email protected] Release State: Final Release Date: January 28, 2008 Confidentiality Company Confidential Category:

Company Confidential 1 © Vyom Technosoft Pvt. Ltd. Vyom XML Course

Contents

1. XML Introduction

2. Retrieving XML using ASP

3. Saving Information in XML Files Using ASP

4. Appending data to Existing XML Files

Company Confidential 2 © Vyom Technosoft Pvt. Ltd. Vyom XML Course

Retrieving XML using ASP For most of the net based organizations, the data stored in their databases are their sole property. How this data can be organized more effectively and efficiently using XML, is the theme of this article.

When you create a database in MS Access, even if it is empty, it takes a lot of space just for structure. Right ? Why waste this much space just for structure when you can store information about at least a hundred members of your site in the same space. When you store data as XML, it is stored in the form of a simple text file with the extension .XML, along with a few tags. For the time being, I will not go in the detailed theory of explaining the intricacies of XML, but rather concentrate on how to access and manipulate it using ASP.

Before we begin, what all is required for your web server to be able to serve XML. For the Server Side XML Processing, IE 5.0+ must be installed on the server. This is because we need XML DOM (XML Document Object Model), which is basically an XML Parser, which is provided as a component of IE5.

Now we are ready to write our scripts. We need two things.

 Data Source  ASP Script to manipulate the data.

Let us first create a data source. Suppose we want to maintain a resource repository in which we want to include a brief description of the resource, its link on the web and its link text. The Sample XML data source for this can be:

(Contents of File Resource.XML)

This program allows you to encrypt your HTML Source Codes so that no one can steal and Copy Paste them in their own site. ftp://ftp.cedium.net/internet/htmlcrypt/encryptHTML.exe HTML Source Code Encryption 736 KB Company Confidential 3 © Vyom Technosoft Pvt. Ltd. Vyom XML Course

DOS Based Eliza Program. Eliza is a Computer program that can talk to you like a human being. Makes use of Artificial Intelligence. http://hps.elte.hu/~gk/Eliza/ELIZA.EXE Eliza Chatterbot 36 KB

Now we write a script to access this data and display it on the web page. I result will be generated in a very simple format, to make the ASP Code simple to understand.

To begin with, we need to create an XML DOM object on the server. This can be done with a line as simple as :

<% Set objXML = Server.CreateObject("Microsoft.XMLDOM") %>

Now we need to give the path of our data source. So add the following line to the code:

<% objXML.Load (Server.MapPath("Resource.xml"))

If objXML.parseError.errorCode <> 0 Then Response.Write "

Error loading the Resource file.

" Response.End End If %>

If the XML DOM Parser throws any error, then we catch that and display the error message.

We want to display the list of all the resources in the file Resource.xml. We know that the resources are enclosed within tag. So, the next step is to create a list of all the objects under the tag .

Company Confidential 4 © Vyom Technosoft Pvt. Ltd. Vyom XML Course

<% Set objLst = objXML.getElementsByTagName("Resource") %>

The Length property of object list indicates the number of items in the list. For example, in our example of Resource.xml, there are two records under the tag. So, objLst.Length shows the value 2, when displayed.

<% Response.write "There are " & objLst.Length & " resources on this site." %>

This is quite interesting upto now. What about accessing individual sub-items ? Suppose we just want to display the URLs of all the resources in our 'database', how can we do that ?

Create one more object, now referring to the items inside the object list. The sub- items can be accessed by using childNodes(index). See this code for further understanding :

<% ' for each resource in the list For i = 0 To objLst.Length - 1

Set subLst = objLst.item(i)

Response.write "

" & vbcrlf Response.Write "" _ & subLst.childNodes(1).childNodes(0).Text & "" Next %>

A careful look at the structure of the XML document that we had created earlier reveals that is inside which is second element of the (first being ). If we start our indexing from 0 (Zero), then is the first element of and is the Zeroeth element inside . That's why I have written the line: subLst.childNodes(1).childNodes(0).Text which is nothing but . Re-read the previous paragraph if you are still not clear and I am sure you will get it soon.

So, the final source code of the ASP file we have created for displaying the URL of all the resources in our database is:

Company Confidential 5 © Vyom Technosoft Pvt. Ltd. Vyom XML Course

<% ' creating an object of XMLDOM Set objXML = Server.CreateObject("Microsoft.XMLDOM")

' Locating our XML database objXML.Load (Server.MapPath("Resource.xml"))

' checking for error If objXML.parseError.errorCode <> 0 Then Response.Write "

Error loading the Resource file.

" Response.End End If

' referring to Resource Set objLst = objXML.getElementsByTagName("Resource") Response.write "There are " & objLst.Length & " resources on this site ."

' for each resource For i = 0 To objLst.Length - 1

' refer to sub-item Set subLst = objLst.item(i)

'display the URL Response.Write "" _ & subLst.childNodes(1).childNodes(0).Text & "" Next %>

Of course, you would need to add all those formatting HTML tags to make this list more attractive. But the core remains the same.

Conclusion:

In this article, we learned how to retrieve the 'records' from XML 'database'. For complete Database related operations, we must know how to insert, update and delete the records from the Scripts. In the next article, we will see how to perform these operations as well.

Saving Information in XML Files Using ASP

Now when you know how to retrieve data from XML files, the next thing you have to learn is, how to create these XML files from ASP. In this Section of the tutorial, I demonstrate how to store data in XML files.

Company Confidential 6 © Vyom Technosoft Pvt. Ltd. Vyom XML Course

Advantages of storing data in XML, as compared to in MS Access are:

 XML is platform independent. You can export your data to Non-Windows OS also.  XML data contains semantics along with it. This means that you can associate a name and property with data. Further, it is Hierarchical data. So, it gets all those advantages of storing data in the form of Trees, in-built in it !  XML consumes much-much less space than MS Access data.  XML data can be used in EDI (Electronic Data Interchange). It can also be used in presenting the data in different formats. Like publishing the same data in PDF, HTML, DOC, PS ... formats.

There are many more advantages of using XML. Try google to find out more (rather bookish) advantages. That's not more important for us. We continue with our business - Saving data (or information, if it really means!) to XML Files.

In this exercise, three files are involved:

 HTML Form File  ASP Processing Script  XML Data File

HTML Form File:

Let us first create the HTML Source file, the easiest of three. The screen looks something like this.

Company Confidential 7 © Vyom Technosoft Pvt. Ltd. Vyom XML Course

The various form field names are given as: title, url, description, size and Submit, in the top-down order as shown above.

Now we write an ASP Script, that will store this data in the XML file. In the current section, we concentrate on just saving the data in a file. If the file already exists, then it will be deleted and then again, contents will be written into it. In the next section, we will see how to append data to an existing file.

So, we proceed further. As done in previous section, we first create an object of Microsoft.XMLDOM.

<% Set objXML = server.CreateObject("Microsoft.XMLDOM") objXML.preserveWhiteSpace = True %>

Here the second line indicates that we want to preserve the White Spaces in the file. Now we create the root element of the document and attach it with the XML document. Look at the XML document structure given at the beginning of this article, to find that the root element is Resource_Repository.

Company Confidential 8 © Vyom Technosoft Pvt. Ltd. Vyom XML Course

<% Set objRoot = objXML.createElement("Resource_Repository") objXML.appendChild objRoot %>

Now we create a new element and place it under Resource_Repository. A quick glance at the structure reveals that the direct child of Resource_Repository is Resource. The immediate child of Resource is , which stores the resource description. So, three steps are involved in creating a child.

 Create the element  Assign value to the element (optional)  Make this new element child of some other element.

The following code demonstrates the first and last of above steps.

<% 'Create an element, "Resource". Set objResource = objXML.createElement("Resource")

' Make a child of Root ' objRoot.appendChild objResource %>

Now we create another element which stores the description of the resource. We follow all the 3 steps mentioned earlier in this case. Try to figure them out in the following code:

<% 'Create a new element, "text". This stor ' es Description of the resource Set objText = objXML.createElement("text")

' Assign the description to the newly cr ' eated object objText.Text = Request.Form("description")

' Make Text (description) a child of Res ' ource objResource.appendChild objText %>

Easy, isn't it ? Now look at the following code and observe the symmetry. Please note that this code is written in accordance with the structure of XML document (Resource.xml) defined at the start of the article.

<% ' create another child of ' ie Set objLink = objXML.createElement("Link")

' make a child of ' objResource.appendChild objLink

' create one more element - &nbs ' p; Set objUrl = objXML.createElement("url")

Company Confidential 9 © Vyom Technosoft Pvt. Ltd. Vyom XML Course

' capture URL value from the form and as ' sign it to ' the newly created element ' objUrl.Text = Request.Form("url")

' make a child of ' objLink.appendChild objUrl

' create a element, assign ' it a value ' and make it a child of Set objLineText = objXML.createElement("linetext") objLineText.Text = Request.Form("title") objLink.appendChild objLineText

' and finally create an element and make ' it a child of Set objSize = objXML.createElement("Size") objSize.Text = Request.Form("size") objResource.appendChild objSize %>

Now we are done with the structure of the document. The next step is to create a Processing Instruction (PI) indicating the XML file version, which appears as the first line of any XML document.

<% 'Create the xml processing instruction.< ' br> Set objPI = objXML.createProcessingInstruction("xml", "version='1.0'")

'Append the processing instruction to th ' e XML document. objXML.insertBefore objPI, objXML.childNodes(0) %>

And as a penultimate step, save the XML file.

<% 'Save the XML document. objXML.save strXMLFilePath & "\" & strFileName %>

Assuming strXMLFilePath and strFileName to be two variables. And finally, free all the objects.

<% 'Release all of your object references.< ' br> Set objXML = Nothing Set objRoot = Nothing Set objResource = Nothing Set objText = Nothing Set objLink = Nothing Set objUrl = Nothing Set objLineText = Nothing Set objSize = Nothing %>

Company Confidential 10 © Vyom Technosoft Pvt. Ltd. Vyom XML Course

This concludes our discussion of saving data to XML files. Before we wrap-up, here is the complete code, which is well formatted in the form of a function.

<%

'------' ------'The "SaveFormData" Function accepts two ' parameters. 'strXMLFilePath - The physical path wher ' e the XML file will be saved. 'strFileName - The name of the XML file ' that will be saved. '------' ------

Function SaveFormData(strXMLFilePath, strFileName)

'Declare local variables. Dim objXML Dim objRoot Dim objField Dim objFieldValue Dim objattID Dim objattTabOrder Dim objPI Dim x

'Instantiate the Microsoft XMLDOM. Set objXML = server.CreateObject("Microsoft.XMLDOM") objXML.preserveWhiteSpace = False

'Create your root element and append it ' to the XML document. Set objRoot = objXML.createElement("Resource_Repository") objXML.appendChild objRoot

'Create an element, "Resource". Set objResource = objXML.createElement("Resource")

' Make a child of Root ' objRoot.appendChild objResource

'Create a new element, "text". This stor ' es Description of the resource Set objText = objXML.createElement("text")

' Assign the description to the newly cr ' eated object objText.Text = Request.Form("description")

' Make Text (description) a child of Res ' ource objResource.appendChild objText

' create another child of ' ie Set objLink = objXML.createElement("Link")

' make a child of ' Company Confidential 11 © Vyom Technosoft Pvt. Ltd. Vyom XML Course objResource.appendChild objLink

' create one more element - &nbs ' p; Set objUrl = objXML.createElement("url")

' capture URL value from the form and as ' sign it to ' the newly created element ' objUrl.Text = Request.Form("url")

' make a child of ' objLink.appendChild objUrl

' create a element, assign ' it a value ' and make it a child of Set objLineText = objXML.createElement("linetext") objLineText.Text = Request.Form("title") objLink.appendChild objLineText

' and finally create an element and make ' it a child of Set objSize = objXML.createElement("Size") objSize.Text = Request.Form("size") objResource.appendChild objSize

'Create the xml processing instruction.< ' br> Set objPI = objXML.createProcessingInstruction("xml", "version='1.0'")

'Append the processing instruction to th ' e XML document. objXML.insertBefore objPI, objXML.childNodes(0)

'Save the XML document. objXML.save strXMLFilePath & "\" & strFileName

'Release all of your object references.< ' br> Set objXML = Nothing Set objRoot = Nothing Set objResource = Nothing Set objText = Nothing Set objLink = Nothing Set objUrl = Nothing Set objLineText = Nothing Set objSize = Nothing End Function

'Do not break on an error. On Error Resume Next

'Call the SaveFormData function, passing ' in the physical path to 'save the file to and the name that you ' wish to use for the file. SaveFormData "C:\Inetpub\wwwroot\save\data","Resource.xml"

Company Confidential 12 © Vyom Technosoft Pvt. Ltd. Vyom XML Course

'Test to see if an error occurred, if so ' , let the user know. 'Otherwise, tell the user that the opera ' tion was successful. If err.number <> 0 then Response.write("Errors occurred while saving data.") Else Response.write("

Data Entry Successful

The resource has been successfully added in the database.

") End If %>

Download the file associated with the article and test the code on your machine. Do not forget to change the path to which the file has to be saved. (This line has been shown in strong fonts in above code listing).

Appending data to Existing XML Files

In Section 2, we saw how we can save form data to XML files. But if the file already existed, then it used to get replaced with the new ones. Most of the times we want to append data, i.e., add new data to the existing ones. In this Section of the tutorial, we look at how we can do so.

The major difference between appending and creating new file is the Processing Instruction (PI) mentioned in the earlier section. When we append data to an existing file, we do not add PI to it (obviously, since it is already there!).

So, we first need to check whether the file already exists. This can be done with the following simple code:

<% blnFileExists = objXML.Load(strXMLFilePath & "\" & strFileName) %>

If the file already exists, then we need to set objRoot to the already existing Root element (Resource_Repository). If the file does not exist, we create a new root element and attach it to XML document, as we did in Section 2.

<% 'Test to see if the file loaded successf ' ully. If blnFileExists = True Then 'If the file loaded set the objRoot Obje ' ct equal to the root element 'of the XML document. Set objRoot = objXML.documentElement Else 'Create your root element and append it to the XML document. Set objRoot = objXML.createElement("Resource_Repository") objXML.appendChild objRoot End If %>

After this we extract the data from the form and store it in the elements, exactly in the same way as we did in Section 2. In the end, write the following code:

Company Confidential 13 © Vyom Technosoft Pvt. Ltd. Vyom XML Course

<% ' Check once again to see if the file lo ' aded successfully. If it did ' not, that means we are creating a new ' document and need to be sure to ' insert the XML processing instruction. ' If blnFileExists = False then 'Create the xml processing instruction.& ' nbsp; Set objPI = objDom.createProcessingInstruction("xml", "version='1.0'") 'Append the processing instruction to th ' e XML document. objDom.insertBefore objPI, objDom.childNodes(0) End If %>

The complete code for appending the data is:

<%

'------' ------'The "AppendFormData" Function accepts t ' wo parameters. 'strXMLFilePath - The physical path wher ' e the XML file will be saved. 'strFileName - The name of the XML file ' that will be saved. '------' ------

Function AppendFormData(strXMLFilePath, strFileName)

'Declare local variables. Dim objXML Dim objRoot Dim objField Dim objFieldValue Dim objattID Dim objattTabOrder Dim objPI Dim x

'Instantiate the Microsoft XMLDOM. Set objXML = server.CreateObject("Microsoft.XMLDOM") objXML.preserveWhiteSpace = False

blnFileExists = objXML.Load(strXMLFilePath & "\" & strFileName)

'''''''''''''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''' ' This part is changed ' '''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''

Company Confidential 14 © Vyom Technosoft Pvt. Ltd. Vyom XML Course

'Test to see if the file loaded successf ' ully. If blnFileExists = True Then 'If the file loaded set the objRoot Obje ' ct equal to the root element 'of the XML ' document. Set objRoot = objXML.documentElement Else 'Create your root element and append it ' to the XML document. Set objRoot = objXML.createElement("Resource_Repository") objXML.appendChild objRoot End If

'''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''

'Create an element, "Resource". Set objResource = objXML.createElement("Resource")

' Make a child of Root ' objRoot.appendChild objResource

'Create a new element, "text". This stor ' es Description of the resource Set objText = objXML.createElement("text")

' Assign the description to the newly cr ' eated object objText.Text = Request.Form("description")

' Make Text (description) a child of Res ' ource objResource.appendChild objText

' create another child of ' ie Set objLink = objXML.createElement("Link")

' make a child of ' objResource.appendChild objLink

' create one more element - &nbs ' p; Set objUrl = objXML.createElement("url")

' capture URL value from the form and as ' sign it to ' the newly created element ' objUrl.Text = Request.Form("url")

' make a child of ' objLink.appendChild objUrl

Company Confidential 15 © Vyom Technosoft Pvt. Ltd. Vyom XML Course

' create a element, assign ' it a value ' and make it a child of Set objLineText = objXML.createElement("linetext") objLineText.Text = Request.Form("title") objLink.appendChild objLineText

' and finally create an element and make ' it a child of Set objSize = objXML.createElement("Size") objSize.Text = Request.Form("size") objResource.appendChild objSize

'''''''''''''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''' ' This part is changed' '''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''

'Check once again to see if the file loa ' ded successfully. If it did 'not, that means we are creating a new d ' ocument and need to be sure to 'insert the XML processing instruction.< ' br> If blnFileExists = False then

'Create the xml processing instruction.< ' br> Set objPI = objDom.createProcessingInstruction("xml", "version='1.0'")

'Append the processing instruction to th ' e XML document. objDom.insertBefore objPI, objDom.childNodes(0) End If

'''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''

'Save the XML document. objXML.save strXMLFilePath & "\" & strFileName

'Release all of your object references.< ' br> Set objXML = Nothing Set objRoot = Nothing Set objResource = Nothing Set objText = Nothing Set objLink = Nothing Set objUrl = Nothing Set objLineText = Nothing Set objSize = Nothing End Function

'Do not break on an error.

Company Confidential 16 © Vyom Technosoft Pvt. Ltd. Vyom XML Course

On Error Resume Next

'Call the AppendFormData function, passi ' ng in the physical path to 'save the file to and the name that you ' wish to use for the file. AppendFormData "C:\Inetpub\wwwroot\append\data","Resource.xml"

'Test to see if an error occurred, if so ' , let the user know. 'Otherwise, tell the user that the opera ' tion was successful. If err.number <> 0 then Response.write("Errors occurred while saving data.") Else Response.write("

Data Entry Successful

The resource has been successfully added in the database.

") End If %>

Company Confidential 17 © Vyom Technosoft Pvt. Ltd.

Recommended publications